<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="allLoading"> </a-spin>
      <a-modal
        width="1000px"
        v-model="detailsVisible"
        title="设备升级"
        @cancel="() => ((this.detailsVisible = false))"
      >
        <template slot="footer">
          <Button type="reset" label="关闭" :disabled="loading" @click="()=>{ this.detailsVisible = false }"></Button>
        </template>
        <div id="modalContent">
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-card title="远程升级">
                <template #extra>
                  <Button type="search" :disabled="loading" :loading="loading" label="升级" @click="onSubmit"></Button>
                </template>
                <a-row type="flex" justify="space-between">
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="版本号"
                      prop="version"
                      placeholder="请输入版本号"
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="FTP地址"
                      prop="ftpAddress"
                      placeholder="请输入FTP地址"
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="FTP用户名"
                      prop="ftpUsername"
                      placeholder="请输入FTP用户名"
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="FTP密码"
                      prop="ftpPassword"
                      placeholder="请输入FTP密码"
                    ></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input
                      :form="form"
                      label="软件包名称"
                      prop="packageName"
                      placeholder="请输入软件包名称"
                    ></Input>
                  </a-col>
                </a-row>
              </a-card>
              <br />
              <a-card title="已选设备编号">
                <a-tag style="margin: 3px;" v-for="(item, index) in selectedRows" :key="index"> {{ item.code }}</a-tag>
              </a-card>
              <br />
              <a-card title="结果">
                <a-row type="flex" justify="space-between">
                  <a-col :span="24">
                    <Textarea
                      :label-col="{ span: 3 }"
                      :wrapper-col="{ span: 21 }"
                      :form="form"
                      label="返回结果"
                      prop="text"
                      placeholder=" "
                      readonly
                    ></Textarea>
                  </a-col>
                </a-row>
              </a-card>
            </a-form-model>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">设备升级</div>
          <div class="addButton">
            <span style="margin-right: 8px" v-show="selectedRows.length > 0">
              {{ `当前选择 ${selectedRows.length} 条数据` }}
            </span>
            <Button type="search" label="设备升级" :disabled="selectedRows.length === 0" @click="handleEdit()"></Button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
            @selectionChange="(e, rows) => { this.selectedRows = rows; }"
          >
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import {
  listCabinets,
  listNetworksAll,
  allCabinetModels,
  sendSoftwareUpgrade
} from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
import Textarea from '@/components/typicalControl/textarea';
import { getYesNo } from '@/utils/frequentInterface';
export default {
  name: 'EquipmentUpgrade',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    treeSelect: treeSelect,
    Select: Select,
    Button: Button,
    Textarea: Textarea
  },
  data() {
    return {
      allLoading: false,
      loading: false,
      detailsVisible: false,
      form: {
        version: undefined,
        ftpAddress: '124.207.112.70',
        ftpUsername: 'dpcpower',
        ftpPassword: 'dpcpower',
        packageName: undefined,
        text: ''
      },
      rules: {
        // 规则验证
        version: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        ftpAddress: [
          { required: true, message: '请输入FTP地址', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        ftpUsername: [
          { required: true, message: '请输入FTP用户名', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        ftpPassword: [
          { required: true, message: '请输入FTP密码', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        packageName: [
          { required: true, message: '请输入软件包名称', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过15个字', trigger: 'blur' }
        ]
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchKeyWord',
            value: '',
            label: '名称或编码'
          },
          {
            type: 'select',
            prop: 'searchNetworkId',
            value: undefined,
            label: '场站网点',
            optList: []
          },
          {
            type: 'select',
            prop: 'searchModelId',
            value: undefined,
            label: '设备型号',
            optList: []
          },
          {
            type: 'select',
            prop: 'searchIsEnable',
            value: undefined,
            label: '是否启用',
            optList: this.getYesNo()
          }
        ],
        parent: this
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            ellipsis: true
          },
          {
            title: '充电桩编号',
            dataIndex: 'code',
            ellipsis: true
          },
          {
            title: '组织机构',
            dataIndex: 'organization.name',
            ellipsis: true
          },
          {
            title: '场站网点',
            dataIndex: 'network.name',
            ellipsis: true
          },
          {
            title: '设备型号',
            dataIndex: 'model.name',
            ellipsis: true
          },
          {
            title: '仓个数',
            dataIndex: 'binCount',
            ellipsis: true
          },
          {
            title: '联网状态',
            dataIndex: 'isOnLine',
            scopedSlots: { customRender: 'isYesNo' },
            width: '80px'
          }
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
        isSelection: true
      },
      // 列表组件数据
      tableData: {
        content: [],
        totalElements: 0
      },
      oDictionary: {
        listNetworksAll: [],
        allCabinetTypes: []
      },
      currentIndex: 0,
      selectedRows: []
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getYesNo,
    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      // 场站网点
      listNetworksAll({ searchDataRang: 9 }).then(res => {
        if (res.code == 200) {
          this.oDictionary.listNetworksAll = res.data;
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop === 'searchNetworkId') {
              this.searchConfig.formItemList[i].optList = res.data.map(n => {
                return {
                  name: n.name,
                  code: n.id
                };
              });
              break;
            };
          }
        }
      });
      // 型号信息
      allCabinetModels().then(res => {
        if (res.code == 200) {
          this.oDictionary.allCabinetTypes = res.data;
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop === 'searchModelId') {
              this.searchConfig.formItemList[i].optList = res.data.map(n => {
                return {
                  name: n.name,
                  code: n.id
                };
              });
              break;
            };
          }
        }
      });
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.allLoading = true;
      searchParam.searchDataRang = 9;
      listCabinets(searchParam).then(res => {
        if (res.code == 200 && res.data.content) {
          this.tableData = res.data;
        } else {
          this.tableData.content = [];
          this.tableData.totalElements = 0;
        }
      }).finally(() => {
        this.allLoading = false;
      });
    },
    /**
     * @description: 新增编辑设备信息表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.currentIndex = 0;
          this.loading = true;
          this.upgradeManage();
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        version: undefined,
        ftpAddress: '124.207.112.70',
        ftpUsername: 'dpcpower',
        ftpPassword: 'dpcpower',
        packageName: undefined,
        text: ''
      };
    },

    handleEdit() {
      this.form = this.initializationForm();
      this.detailsVisible = true;
    },

    /**
     * [upgradeManage 批量升级管理器]
     * @return {[type]} [description]
     */
    upgradeManage() {
      if (this.currentIndex < this.selectedRows.length) {
        this.addUpgrade(this.selectedRows[this.currentIndex].id, this.selectedRows[this.currentIndex].code);
      } else {
        console.log('批处理结束');
        this.loading = false;
      }
    },

    /**
     * [addUpgrade 添加升级]
     * @param {[type]} id   [充电柜id]
     * @param {[type]} code [充电柜code]
     */
    addUpgrade(id, code) {
      sendSoftwareUpgrade({ id: id, body: this.form })
        .then(res => {
          res.dataCode = code;
          this.formOperation(res);
        }).catch(err => {
          err.response.data.dataCode = code;
          this.formOperation(err.response.data);
        }).finally(() => {
          this.currentIndex++;
          this.upgradeManage();
        });
    },

    /**
     * [formOperation 消息更新上form]
     * @param  {[type]} res [表单请求后返回的对象]
     * @return {[type]}     [description]
     */
    formOperation(res) {
      if (this.form.text) {
        this.form.text = this.form.text + '\n编号' + res.dataCode + ': ' + res.message;
      } else {
        this.form.text = '编号' + res.dataCode + ': ' + res.message;
      }
    },

    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    }
  }
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 40%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 500px;
  overflow: auto;
  position: relative;
}
</style>
